Where in the above code is a constructor being used?
HelloObject anObject = new HelloObject("A Greeting!"); ------------------------------What is its parameter? A reference to the string "A Greeting!"
The class needs a constructor. Constructor definitions look like this:
className( parameterList ) { Statements that usually use the variables of the class and the parameters in the parameterList. }
No return type is listed in front of className.
The return type is automatically a reference to an object of the class.
There is no return
statement in the body of the constructor.
A reference is automatically returned without you asking for it.
(There would be no reason to have a constructor, otherwise.)
The constructor has the same name as the class.
The parameterList is a list of values and their types that
will be sent to the constructor when it makes a new object.
Parameter lists look like this (the same as parameter lists for methods):
TypeName1 parameterName1, TypeName2 parameterName2, ... as many as you need
It is OK to have an empty parameter list. A class often has several constructors with different parameters. Each one builds the same class of object, but will initialize it differently.
Usually the method that invokes a constructor saves the returned reference in a variable. But sometimes an object is constructed for temporary use and its reference is not saved. The object is used but once for some brief purpose and then becomes garbage.